<script setup>
import { ref } from 'vue'
import { userLogin } from '@/api/user'
import router from '@/router'
import { ElMessage } from 'element-plus'


const ruleForm = ref({
  username: '',
  password: '',
})
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: 'Length should be 3 to 6', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 50, message: 'Length should be 3 to 50', trigger: 'blur' },
  ]
})
const ruleFormRef = ref(null)
const submitForm = () => {
  if (!ruleFormRef) return
  ruleFormRef.value.validate(async(valid) => {
    if (valid) {
      let res = await userLogin(ruleForm.value)
      if (res.code === 1) {
        ElMessage.success('登录成功')
        localStorage.setItem('userLogin',JSON.stringify(res.data))
        router.push('/')
        
      }else{
        ElMessage.error('登录失败')
      }
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = () => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<template>
  <div class="container">
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password"  />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">登录</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>
<style scoped>
.container {
   min-height: 100vh;       /* 占据整个视口高度 */
  padding: 20px;            /* 可选：防止贴边 */
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}
.demo-ruleForm {
  padding: 20px;
  border: 1px solid #eee;
}

</style>